#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author  : micah
# @time    :  
# @function: 
# @version :


import asyncio
import os
import aiohttp
import time
import requests


class spider_Img():
    def __init__(self):
        self.url = 'https://pvp.qq.com/web201605/js/herolist.json'
        self.skin_url = 'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/{}/{}-bigskin-{}.jpg'
        self.headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'
        }

    async def download_img(self, client, ename, cname):
        for i in range(1, 20):
            response = await client.get(self.skin_url.format(ename, ename, i), headers=self.headers)
            if response.status == 200:
                # 获取图片进制read读取
                content = await response.read()
                with open('图片/' + cname + '-' + str(i) + '.jpg', 'wb') as f:
                    f.write(content)
                    print('正在下载{}，第{}张'.format(cname, i))
            else:
                break

    async def main(self):
        async with aiohttp.ClientSession(headers=self.headers) as client:
            response = await client.get(self.url)
            data = await response.json(content_type=None)
            tasks = []
            for i in data:
                ename = i['ename']
                cname = i['cname']
                res = self.download_img(client, ename, cname)
                task = asyncio.create_task(res)
                tasks.append(task)
            await asyncio.wait(tasks)


if __name__ == '__main__':
    if not os.path.exists('图片'):
        os.mkdir('图片')
    start = time.time()
    crawl_image = spider_Img()
    # 获取时间循环 Eventloop 我们想运用协程，首先要生成一个loop对象，然后loop.run_xxx()就可以运行协程了，而如何创建这个loop，方法有两种
    # 对于主线程是loop=get_event_loop().
    loop = asyncio.get_event_loop()
    # 执行协程
    loop.run_until_complete(crawl_image.main())
    print('运行时间{}'.format(time.time() - start))
